import { useCallback, useEffect, useState } from 'react';
import { message } from 'antd';
import { AUTH_STORE, USER_STORE } from '@/constants';
import { resChangeUserinfo, resUserinfo } from '@/services/user';
import { useRequest } from 'ahooks';
import { atom, AtomEffect, useRecoilState } from 'recoil';
import { isValidTokenTime } from '@/utils/auth';
import { local } from '@/utils/storage';

let userinfo: API.Userinfo = {
  avatar: '',
  created_at: '',
  email: '',
  email_verified: '',
  id: 0,
  is_locked: 0,
  name: '',
  phone: '',
  remember_token: '',
  role: 0,
  sign: '',
  updated_at: '',
  username: '',
};

export let resetUserStore: () => void = () => {};

export const useUserStore = () => {
  const [user, setUser] = useRecoilState(userStore);
  const getUserinfo = useCallback(() => {
    resUserinfo().then((data) => {
      setUser(data);
    });
  }, []);

  const { loading, runAsync } = useRequest(resChangeUserinfo, {
    manual: true,
  });
  const changeUserinfo = useCallback(
    (param: API.ChangeUserinfoParams) => {
      runAsync(param).then(() => {
        message.success('修改个人信息成功');
        getUserinfo();
      });
    },
    [runAsync]
  );


  const reset = useCallback(() => {
    setUser({ ...userinfo });
  }, []);
  return {
    user,
    getUserinfo,
    reset,
    changeUserinfo: { changeUserinfo, loading },
  };
};

const subscriptUserStore: AtomEffect<API.Userinfo> = ({
  onSet,
  resetSelf,
  setSelf,
  trigger,
}) => {
  onSet((newValue) => {
    local.set(USER_STORE, newValue);
  });

  const initSelf = async () => {
    const userinfo = await resUserinfo();
    if (userinfo) {
      setSelf(userinfo);
    }
  };

  const auth = local.get<AuthStructure>(AUTH_STORE, { token: '', expire: '' });
  if (auth.token && isValidTokenTime(auth.expire)) {
    initSelf();
  }

  resetUserStore = () => {
    resetSelf();
  };
};

export const userStore = atom<API.Userinfo>({
  key: USER_STORE,
  default: userinfo,
  effects_UNSTABLE: [subscriptUserStore],
});

export default useUserStore;
